<script setup>
  import { getCitysApi } from '@/api/article'
  import { ref } from 'vue'

  defineProps({
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '搜索景点地址'
    }
  })

  defineEmits(['input'])

  const cityOptions = ref([])
  const searchAddress = async (key) => {
    if (!key.trim().length) return
    const { data } = await getCitysApi(key)
    // 解析出所有市层级
    const citys = []
    data.forEach((province) => {
      citys.push(...province.citys.map((city) => ({ ...city, provinceName: province.provinceName })))
    })
    cityOptions.value = citys
  }

  defineExpose({ cityOptions })
</script>

<template>
  <el-select :value="value" @change="$emit('input', $event)" clearable filterable remote reserve-keyword :placeholder :remote-method="searchAddress">
    <el-option v-for="item in cityOptions" :key="item._id" :label="item.provinceName + '-' + item.cityName" :value="item.cityName" />
  </el-select>
</template>

<style scoped lang="scss">
  .el-select {
    min-width: 180px;
  }
</style>
